package com.tsoj.utils;


import com.tsoj.propertise.JwtPropertise;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.util.Map;

/**
 * Jwt工具类
 */
@Component
public class JwtUtils {
    @Autowired
    private  JwtPropertise jwtPropertise;

    /**
     * 生成jwt
     */
    public static String createJwt(Map<String, Object> claims, JwtPropertise jwtPropertise){
        //生成Header
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        //生成过期时间
        long expMillis = System.currentTimeMillis() + jwtPropertise.getUserTtl();//返回当前时间戳
        Date exp = new Date(expMillis);//转换为具体时间
        //设置body
        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .signWith(signatureAlgorithm,jwtPropertise.getUserSecretKey().getBytes(StandardCharsets.UTF_8))
                .setExpiration(exp);
        System.out.println(builder.compact());
        return builder.compact();
    }

    /**
     * 解析jwt
     */
    public static Claims parseJwt(String secretKey, String token){
        if (token == null || token.isEmpty()) {
            throw new JwtException("Token为空");
        }
        Claims claims = null;
        try {
            System.out.println("token:"+token);
            claims = Jwts.parser()
                    .setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
                    .parseClaimsJws(token).getBody();
            System.out.println(claims);
        } catch (ExpiredJwtException e) {
            System.out.println("token解析失败");
        }

        return claims;
    }
}
